package org.rxc.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.rxc.gift.domain.User;
import org.rxc.gift.exception.BusinessException;
import org.rxc.gift.exception.ResponseCode;
import org.rxc.gift.exception.RonghuaAssert;
import org.rxc.gift.service.IUserService;
import org.rxc.gift.service.IVerifyCodeService;
import org.rxc.gift.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String USER_REGISTER_SMS_CODE = "user_register_sms_code_";
    @Override
    public void VerifyCodeSendRegister(String phone) {
        //1.参数校验
        //非空校验
        //检验手机号是否已经注册
        Wrapper<User> wrapper = new EntityWrapper<User>().eq("phone", phone);

        User user = userService.selectOne(wrapper);
        RonghuaAssert.isNull(user, ResponseCode.RESPONSE_CODE_109);

        //2.从redis中获取当前手机号的验证码
        String key =  USER_REGISTER_SMS_CODE+phone;
        sendSmsCode(key);


    }

    @Override
    public String getSmsCode(String phone) {
        String key =  USER_REGISTER_SMS_CODE+phone;
        String smsCode = (String) redisTemplate.opsForValue().get(key);
        RonghuaAssert.isNotBlank(smsCode,ResponseCode.RESPONSE_CODE_107);
        return smsCode;
    }

    private void sendSmsCode(String key) {
        String smsCode = (String) redisTemplate.opsForValue().get(key);
        //3.判断redis中验证码是否存在
        if (StringUtils.isNotBlank(smsCode)){
            //如果存在,就判断当前验证码是否过重发时间
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (expire > 4*60){
                //如果没有过重发时间,就返回错误信息
                throw new BusinessException(ResponseCode.RESPONSE_CODE_110);
            }

        }else {
            //如果不存在,就重新生成验证码
            smsCode = StrUtils.getRandomString(6);
        }
        //并存入redis中,设置过期时间
        redisTemplate.opsForValue().set(key,smsCode,5,TimeUnit.MINUTES);
        //4.发送给用户
        String msg = "你的验证码为"+smsCode+",请在5分钟之内使用";
//        SmsUtil.sendSms(dto.getPhone(),msg);
        System.out.println(msg);
    }

}
